package org.jeecg.modules.wlhy.hydriver.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.*;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.third.daikai.daoda.DaodaService;
import org.jeecg.modules.third.daikai.daoda.dto.AddUserDTO;
import org.jeecg.modules.third.daikai.daoda.dto.AddUserDriverDTO;
import org.jeecg.modules.third.dongjiang.tax.system.dto.ApiBaseResDTO;
import org.jeecg.modules.third.dongjiang.tax.system.dto.req.serviceprovide.ServiceProvideDTO;
import org.jeecg.modules.third.dongjiang.tax.system.service.DongjiangTaxSystemService;
import org.jeecg.modules.third.jg.report.freight.information.util.WebUtils;
import org.jeecg.modules.third.oapi.alct56.constant.enums.ImageCategory;
import org.jeecg.modules.third.oapi.alct56.constant.enums.ImageType;
import org.jeecg.modules.third.oapi.alct56.dto.AlctApiBaseResDTO;
import org.jeecg.modules.third.oapi.alct56.service.OapiAlct56Service;
import org.jeecg.modules.third.openapi.OpenApiService;
import org.jeecg.modules.third.tosapi.constant.enums.YNEnum;
import org.jeecg.modules.third.tosapi.dto.TosApiBaseResDTO;
import org.jeecg.modules.third.tosapi.dto.carrier.CarrierDTO;
import org.jeecg.modules.third.tosapi.service.TosApiService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainDriver;
import org.jeecg.modules.wlhy.captain.mapper.HyCaptainDriverMapper;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydaodauser.entity.HyDaodaUser;
import org.jeecg.modules.wlhy.hydaodauser.service.IHyDaodaUserService;
import org.jeecg.modules.wlhy.hydriver.entity.*;
import org.jeecg.modules.wlhy.hydriver.mapper.HyDriverMapper;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverAccountBookService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriver.vo.HyDriverVehicleVO;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hydrivercustomer.service.IHyDriverCustomerService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyDriverVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.BankTypeUtil;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.jeecg.modules.third.dongjiang.tax.system.constant.TaxConstant.API_TAX_CUSTOMER_SUBFIX;

/**
 * @Description: 司机管理
 * @Author: duanlikao
 * @Date:   2020-12-02
 * @Version: V1.0
 */
@Service
@Slf4j
public class HyDriverServiceImpl extends ServiceImpl<HyDriverMapper, HyDriver> implements IHyDriverService {

    @Value(value = "${customer.driver-depart-id}")
    private String driverDepartpid;

    @Value(value = "${customer.driver-role-id}")
    private String driverRoleID;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private ISysDepartService departService;

    @Autowired
    private ISysUserDepartService sysUserDepartService ;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserRoleService sysUserRoleService ;

    @Autowired
    private IHyDriverVehicleService hyDriverVehicleService;

    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Resource
    private HyDriverMapper hyDriverMapper;


    @Resource
    private IHySettingService settingService;

    @Resource
    private DongjiangTaxSystemService dongjiangTaxSystemService;

//    @Autowired
//    private IHyWarningMessageService hyWarningMessageService;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private IHyVehicleService iHyVehicleService;
    @Autowired
    private IHyDriverVehicleService iHyDriverVehicleService;
    @Autowired
    private IHyDriverBankService iHyDriverBankService;
    @Autowired
    private IHyDriverAccountBookService iHyDriverAccountBookService;

    @Autowired
    private DaodaService daodaService;

    @Autowired
    private IHyDaodaUserService hyDaodaUserService;

    @Autowired
    private OapiAlct56Service oapiAlct56Service;
    @Autowired
    private TosApiService tosApiService;


//    @Autowired
//    private IHyDriverService hyDriverService;


    private static final Logger LOGGER = LoggerFactory.getLogger(HyDriverServiceImpl.class);

    @Autowired
    private IHyDriverCustomerService hyDriverCustomerService;

    @Resource
    private HyCaptainDriverMapper captainDriverMapper;
    @Autowired
    private IHyCaptainService captainService;

    @Override
    @Transactional
    public Result<?> saveHyDriver(HyDriver hyDriver) {
        if (hyDriver.getIdcard().length() != 15 && hyDriver.getIdcard().length() != 18) {
            throw new JeecgBootException("身份证应为15位或者18位。");
        }
        if (!IDUtils.isIDNumber(hyDriver.getIdcard())) {
            throw new JeecgBootException("请填写正确身份证！");
        }
        if (hyDriver.getTelephone().length() != 11) {
            throw new JeecgBootException("手机号应为11位数。");
        }
        if (!hyDriver.getTelephone().matches(CommonConstant.REGEX_MOBILE)) {
            throw new JeecgBootException("手机号格式错误！");
        }
//        if(hyDriver.getIzAffiliation().equals("1")){
//            if(StringUtils.isEmpty(hyDriver.getAffiliationAgreement())){
//                throw new JeecgBootException("挂靠协议不能为空！");
//            }
//        }

       String checkDriverClass =  HyCfgUtil.getCfgValue("check_driver_class") ;
        if (StringUtils.isBlank(checkDriverClass)) {
            throw new JeecgBootException("请联系平台管理添加司机准驾车类型！");
        }
        //String as = "A1、A2、A2F、A1A2、A2A3、A1A2D、A1A2E、A3、B1、B2、B1B2、B1B2D、A2D、A2E、A2M、B2D、B2E、B2M、A1D、A1E、A1M、B1D、B1E、B1M、C1";
        int result1 = checkDriverClass.indexOf(hyDriver.getVehicleClass());
        if (StringUtils.isNotEmpty(hyDriver.getVehicleClass()) && result1 == -1) {
//            hyDriver.setExamineDate(new Date());
//            hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_AUDIT_FAILURE.getCode());
//            hyDriver.setExaminRemark("您的驾驶类型不正确,请核对或者联系管理员！");
            throw new JeecgBootException("您的驾驶类型不正确,请核对或者联系管理员！");
        }
        Result<JSONObject> result = new Result<JSONObject>();

        QueryWrapper<HyDriver> driverQueryWrapper = new QueryWrapper();
        driverQueryWrapper.eq("idcard",hyDriver.getIdcard());
        HyDriver queryHyDriverByIdcard =  getOne(driverQueryWrapper);
        if(StringUtils.isBlank(hyDriver.getId()) && queryHyDriverByIdcard !=null ){
            throw new JeecgBootException("您的司机身份证信息已经注册过了，请勿重复注册！");
        }

        HyDriver queryHyDriver = null;
        if (StringUtils.isNotEmpty(hyDriver.getUserId())) {
            queryHyDriver = hyDriverMapper.getHyDriverByUserId(hyDriver.getUserId());
        }
        if (queryHyDriver != null) {
//            if (queryHyDriver.getExamineStatus().equals(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode())) {
//                throw new JeecgBootException("该司机已审核通过，请直接登陆。");
//            }
            hyDriver.setId(queryHyDriver.getId());
        }

        //获取部门orgCode
        //String orgCode  = departService.getMyDeptParentOrgCode(driverDepartpid);
        SysDepart sysDepart = departService.getSysDepartById(driverDepartpid);
        if (StringUtils.isNotEmpty(hyDriver.getUserId())) {
            SysUser user = sysUserService.getById(hyDriver.getUserId());
            if(!"4".equals(user.getUType())){
                throw new JeecgBootException("该账号不是司机账号");
            }
            //补充登陆账号
            user.setRealname(hyDriver.getDriverName());
            user.setBirthday(hyDriver.getBirthday());
            user.setSex(Integer.getInteger(hyDriver.getSex()));
            sysUserService.updateById(user);
            hyDriver.setTelephone(user.getPhone());
        } else {
            //检查用户是否存在
            SysUser suser = sysUserService.getUserByPhone(hyDriver.getTelephone());
            HyDriver queryHoneHyDriver = getHyDriverByTelephone(hyDriver.getTelephone());
            if (suser != null || queryHoneHyDriver != null) {
                throw new JeecgBootException("该司机手机号已存在,不能重复注册");
            }
            SysUser user = new SysUser();
            //String username = hyDriver.getTelephone();//设置登陆账号为手机号
            String username = sysUserService.createRandomUserName();//随机生成账号
            user.setUsername(username);
            user.setRealname(hyDriver.getDriverName());
            user.setPhone(hyDriver.getTelephone());
            //设置创建时间
            user.setCreateTime(new Date());
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            //设置默认密码123456
            user.setPassword("Aa.123456");
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setBirthday(hyDriver.getBirthday());
            user.setSex(Integer.getInteger(hyDriver.getSex()));
            user.setOrgCode(sysDepart.getOrgCode());
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setUType("4");
            sysUserService.addUserWithRole(user, driverRoleID);
            sysUserService.addUserWithDepart(user, sysDepart.getId());

            hyDriver.setUserId(user.getId());
        }

//        驾驶员从业资格证号，使用总质量 4.5 吨及以下普通货运车辆从事普通货物运
//        输经营的驾驶员，填写“驾驶员身份证前 6 位+000000000000”。
        if ("2".equals(hyDriver.getWeightType())) {
            hyDriver.setQualificationCertificate(hyDriver.getIdcard().substring(0, 6) + "000000000000");
        }
        if (hyDriver.getSysOrgCode() == null) {
            hyDriver.setSysOrgCode(sysDepart.getOrgCode());
        }
        hyDriver.setAreaCode( hyDriver.getIdcard().substring(0 , 6) );
        hyDriver.setDrivingLicense(hyDriver.getIdcard());
        boolean resultSave = false;
        //新增
        if (StringUtils.isEmpty(hyDriver.getId()) && queryHyDriver == null) {
            hyDriver.setIzUsed("0");
            resultSave = this.save(hyDriver);
        } else { //更新
            resultSave = this.updateById(hyDriver);
        }
        if (resultSave) {
            result.setSuccess(true);
            result.setCode(CommonConstant.SC_OK_200);
            result.setMessage("司机信息保存成功!");
            result.setResult(
                    JSONObject.parseObject(JSONObject.toJSONString(hyDriver))
            );
            //司机 货主添加关系表
            hyDriverCustomerService.addDriverCustomer(hyDriver.getId(),userUtil.getCustomerById());
            if (userUtil.isCaptain()){
                //司机、承运商添加关系表
                HyCaptainDriver captainDriver = new HyCaptainDriver();
                captainDriver.setCaptainId(captainService.getInfoByUserId(userUtil.getLoginUser().getId()).getId());
                captainDriver.setDriverId(hyDriver.getId());
                captainDriverMapper.insert(captainDriver);
            }
            return result;
        }else{
            result.setSuccess(false);
            result.setCode(CommonConstant.REGISTER_FAILED);
            result.setMessage("司机信息保存失败,请重新提交信息！");
            result.setTimestamp((new Date()).getTime());
            return result;
        }
    }



    /**
     * 聚合数据--驾驶证信息查询姓名
     *
     * @param IDCardNo
     * @param name
     * @return
     */
    @Override
    public String checkDriver(String IDCardNo, String name) {
        if (StringUtils.isEmpty(IDCardNo) || StringUtils.isEmpty(name)) {
            return null;
        }
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getJuheIzUse()){
            throw new JeecgBootException("聚合数据服务暂未开启,请联系管理员。");
        }
        Map<String, String> params = new HashMap<>();
        params.put("key", systemConfig.getJuheKey());
        params.put("IDCardNo", IDCardNo);
        params.put("name", name);
        String url = "http://v.juhe.cn/licenseInfoCheck/query.php";

        String sendResult = null;
        try {
            sendResult = WebUtils.doPostBuildQuery(url, params, WebUtils.DEFAULT_CHARSET, null);
            if (StringUtils.isNotEmpty(sendResult)) {
                return sendResult;
            }
        } catch (IOException e) {
            LOGGER.info("HyDriverServiceImpl checkDriver  IOException:{}", e.getMessage());
        }
        LOGGER.info("HyDriverServiceImpl checkDriver  url:{} | jsonObject:{}"
                , url, params.toString());
        return null;
    }

    @Override
    public String testCheckDriver() {
        HyDriverServiceImpl driverService = new HyDriverServiceImpl();
        return driverService.checkDriver("232301196112207570", "王军");
    }


    @Override
    public HyDriver getHyDriverByTelephone(String telephone) {
        return hyDriverMapper.getHyDriverByTelephone(telephone);
    }

    @Override
    public HyDriver getHyDriverByUserId(String userId) {
        return hyDriverMapper.getHyDriverByUserId(userId);
    }

    @Override
    public HyDriver getDriverInfo(String id) {
        return getById(id);
    }

    /**
     * 获取当前登陆司机用户信息
     *
     * @return
     */
    @Override
    public Result<?> getDriverUserInfo() {
        Result<JSONObject> result = new Result<JSONObject>();
        SysUser user = userUtil.getUser();
        this.checkValidUser(user);
        //用户信息
        sysUserService.appUserInfo(user, result);
        return result;

    }
    @Override
    public Result<?> getRefreshDriverUserInfo() {
        Result<JSONObject> result = new Result<JSONObject>();
        SysUser user = userUtil.getUser();
        this.checkValidUser(user);
        //用户信息
        SysUserExtend  userExtend =  sysUserService.getRefreshDriverUserInfo(user, result);
        JSONObject obj = new JSONObject();
        obj.put("userInfo", userExtend);
        result.setResult(obj);
        return result;

    }

    /**
     * 检查用户有效性
     *
     * @param user
     */
    @Override
    public HyDriver checkValidUser(SysUser user) {

        //查询用户是否是司机角色
        List<SysUserRole> userRoles = sysUserService.getUserRoles(user.getId());
        boolean isDriverRole = false;
        if (CollectionUtils.isNotEmpty(userRoles)) {
            for (SysUserRole userRole : userRoles) {
                if (driverRoleID.equals(userRole.getRoleId())) {
                    isDriverRole = true;
                    break;
                }
            }
        }
        if (!isDriverRole && !"4".equals(user.getUType())) {
            throw new JeecgBootException("不是司机账号");
        }

        HyDriver hyDriver = getHyDriverByUserId(user.getId());
        //驾驶证信息已经过期，上传资料重新审核。
        if (hyDriver != null && hyDriver.getValidPeriodTo() !=null && hyDriver.getValidPeriodTo().before(new Date())) {
            hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
            hyDriver.setExaminRemark("驾驶证信息已经过期，上传资料重新审核。");
            updateById(hyDriver);
        }


        return hyDriver;
    }

    /**
     * 检查用户有效性
     *
     * @param
     */
    @Override
    public Result checkValidDriver(HyDriver hyDriver) {


        //驾驶证信息已经过期，上传资料重新审核。
        if (hyDriver != null && hyDriver.getValidPeriodTo() !=null && hyDriver.getValidPeriodTo().before(new Date())) {
            hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
            hyDriver.setExaminRemark("驾驶证信息已经过期，上传资料重新审核。");
            updateById(hyDriver);
            return Result.error("驾驶证信息已经过期，上传资料重新审核。");
        }
/*
        //驾驶证信息已经过期，上传资料重新审核。
        if (hyDriver.getQualificationExpiredDate() != null && hyDriver.getQualificationExpiredDate().before(new Date())) {
            hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
            hyDriver.setExaminRemark("从业资格证信息已经过期，上传资料重新审核。");
            updateById(hyDriver);
            return Result.error("从业资格证信息已经过期，上传资料重新审核。");
        }*/


        return Result.OK();
    }

    /**
     * 获取司机当前正在进行的运单
     *
     * @param driverId
     * @return
     */
    @Override
    public List<HyShippingNote> getCurrentShippingNote(String driverId) {

        List<HyShippingNote> shippingNote = shippingNoteService.list(new QueryWrapper<HyShippingNote>()
                .eq("driver_id", driverId)
                .in("shipping_status", "1", "2", "3")
        );
        return shippingNote;
    }

    @Override
    public int getCurrentShippingNoteCount(String driverId) {
       return  shippingNoteService.count(new QueryWrapper<HyShippingNote>()
                .eq("driver_id", driverId)
                .in("shipping_status", "1", "2", "3")
        );
    }


    @Override
    public int getCurrentShippingNoteCount(String driverId, String orderId) {
        return  shippingNoteService.count(new LambdaQueryWrapper<HyShippingNote>()
                .eq(HyShippingNote::getDriverId, driverId)
                .eq(HyShippingNote::getOrderId, orderId)
                .in(HyShippingNote::getShippingStatus, "1", "2", "3")
        );
    }








    /**
     * 人员从业资格证验证
     *
     * @param hyDriverDb
     */
    @Override
    public boolean checkQualificationV2(HyDriver hyDriverDb) {
        if (hyDriverDb == null) {
            throw new JeecgBootException("司机信息为空！");
        }
        if(hyDriverDb.getVehicleClass().contains("C1")){
            return  true;
        }
        //监管上报司机车辆验证开关 关闭不验证
        String updataDrivervehiclValidate = settingService.getSettingValueByTag("updata_drivervehicl_validate");
        if("0".equals(updataDrivervehiclValidate)){
            return  true;
        }

        String provinceCode = hyDriverDb.getIdcard().substring(0, 2)+"0000";
        String resultString = openApiService.checkQualificationV2(hyDriverDb.getDriverName(),
                provinceCode, hyDriverDb.getIdcard(), null);
        if(StringUtils.isNotEmpty(resultString)) {
            JSONObject jsonObject = JSONObject.parseObject(resultString);

            //v3 返回结果
            //JSONObject resultJsonObject = jsonObject.getJSONObject("result");
            //if(1001 == jsonObject.getIntValue("status") && resultJsonObject  != null ){
            //    10000 成功； 10001 查询无结果；10002 参数有误；10003 请求错误；10004 系统错误
            //    if("10000".equals(resultJsonObject.getString("code") ) ) {
            //        if( "有效".equals(resultJsonObject.getString("certificateState")) ){
            //            return  true;
            //        }else{
            //            throw new JeecgBootException("司机人员从业资格证已过期！");
            //        }
            //
            //    }else if("10001".equals(resultJsonObject.getString("code") )){
            //        throw new JeecgBootException("司机人员从业资格证查询无结果！");
            //    }
            //}

            //v2 返回结果
            JSONArray resultJsonObject = jsonObject.getJSONArray("result");
            if(1001 == jsonObject.getIntValue("status") && resultJsonObject.size() > 0  ){
                JSONObject resultJsonObject1  =  resultJsonObject.getJSONObject(0);
                if( "是".equals(resultJsonObject1.getString("certificateExpired")) ) {
                    return true;
                }else{
                    throw new JeecgBootException("司机人员从业资格证已过期！");
                }

            }
        }
        return  false;
    }



    /**
     * 组装天津东疆税务系统服务方（司机）信息
     *
     * @param hyDriver
     * @param hyVehicle
     * @param hyDriverAccountBook
     * @return
     */
    private ServiceProvideDTO driver2ServiceProvideDTO(HyDriver hyDriver, HyVehicle hyVehicle, HyDriverAccountBook hyDriverAccountBook) {
        String sub = uploadpath + File.separator;
        //2.服务方（车主）信息
        ServiceProvideDTO serviceProvideDTO = new ServiceProvideDTO();
        //服务方uuid之前平台如果有使用,没有生成
        if (StringUtils.isNotEmpty(hyDriver.getFwfuuid())) {
            serviceProvideDTO.setFwfuuid(hyDriver.getFwfuuid());// 是 平台生成的服务方唯一标 识（uuid 默认长度 32 位， 建议以平台缩写大写字母 作为前缀，并结合数字+字 母混合形成 32 位唯一标识）
        } else {
            serviceProvideDTO.setFwfuuid(API_TAX_CUSTOMER_SUBFIX + hyDriver.getId());// 是 平台生成的服务方唯一标 识（uuid 默认长度 32 位， 建议以平台缩写大写字母 作为前缀，并结合数字+字 母混合形成 32 位唯一标识）
        }
        serviceProvideDTO.setFwfxm(hyDriver.getDriverName());// 是 服务方（车主）姓名
        serviceProvideDTO.setFwfsfzjlx("201");// 是 身份证件类型-填写身份 证件种类代码，参见《申 报表-计税 excel 页签： 证件代码表》 2019-5-15 说明
        serviceProvideDTO.setFwfsfzjhm(hyDriver.getIdcard());// 是 身份证件号码
        serviceProvideDTO.setYddh(hyDriver.getTelephone());// 是 手机号码
        serviceProvideDTO.setJszjhm(hyDriver.getDrivingLicense());// 是 驾驶证件号码

        String num = hyVehicle.getDrivingLicenseNum();
        if (num == null || num.equals("")){
            num = hyVehicle.getVin();
        }

        serviceProvideDTO.setXszjhm(num);// 是 行驶证件号码(行驶证号 码取行驶证档案编号，如 果行驶证上没有档案编 号 ,可用 vin 代替档案编 号推送为行驶证号码,前 提是传输的行驶证照片 中也没有档案编号) 2019-8-26 说明
        serviceProvideDTO.setCycph(hyVehicle.getVehicleNumber());// 是 承运车牌号
        serviceProvideDTO.setCycx(hyVehicle.getVehicleType());// 是 承运车型

        int[] cycc = new int[3];
        cycc[0] = Integer.parseInt(hyVehicle.getVehicleLong()) / 1000;
        cycc[1] = Integer.parseInt(hyVehicle.getVehicleWidth()) / 1000;
        cycc[2] = Integer.parseInt(hyVehicle.getVehicleHeight()) / 1000;
        int cyccInt = cycc[0] * cycc[1] * cycc[2];
        serviceProvideDTO.setCycc(cyccInt + "");// 是 承运车长（数字+单位 m/ 米 长 * 宽 * 高） 7*2*3  应为number类型的值.

        serviceProvideDTO.setCyzz(hyVehicle.getVehicleTonnage().toString());// 是 承运载重（数字+单位 t/ 吨）
        serviceProvideDTO.setCypp(hyVehicle.getBrandName());// 是 承运车辆品牌
        serviceProvideDTO.setCcnf("");// 否 出厂年份 时间格式例如：2019 2019-7-10 说明-选填 标识
        serviceProvideDTO.setJyrq("");// 否 检验日期 2019-7-10 说明-选填 标识
        serviceProvideDTO.setNsrsbh("");// 否 统一社会信用代码（车主所在企业的纳税人识别号） 2019-7-10 说明-选填
        serviceProvideDTO.setNsrmc("");// 否 纳税人名称（车主所在企业 名称） 2019-7-10 说明-选填 标识
        serviceProvideDTO.setGsdz("");// 否 公司地址（车主所在企业地 址） 2019-7-10 说明-选填 标识

        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        serviceProvideDTO.setPtzcsj(dateFormat1.format(hyDriver.getCreateTime()));// 20 是 服务方注册时间 系统要求格 式:yyyy-MM-dd HH:mm:ss; 例如 ： 2019-05-21 19:10:10 2019-5-22 说明

        String areaCode = hyDriver.getAreaCode().substring(0, 4) + "00";
        serviceProvideDTO.setSsdq(areaCode);// 是 服务方所属地区-填写行 政区划代码（市级），参 见《行政区划代码-名称 表》 2019-5-15 说明

        serviceProvideDTO.setZjcx("");// 否 准驾车型（A1、A2、A3、B1、 B2、C1、C2、C3、C4、 M 等） （可暂缓推送） 2019-7-10 说明-选填 标识
        serviceProvideDTO.setJszlqrq("");// 否 领证日期-驾驶证获取日 期，系统要求格 式:yyyy-MM-dd HH:mm:ss; 例如 ： 2019-05-21 19:10:10 2019-7-10 说明-选填 标识
        //司机银行卡信息
        //serviceProvideDTO.setKhrxm(driverSelfBank.getBankName());// 是 开户人姓名 2019-5-22 新增
        //serviceProvideDTO.setKhrsfzjhm(driverSelfBank.getIdcard());// 是 开户人身份证号 （2019-5-22 新增）
        //String bankName = CheckBankCardIUtil.getBankNameByBankCode(driverSelfBank.getBankType());
        //serviceProvideDTO.setKhyh(bankName);// 是 开户银行(例如光大银行) 2019-5-22 新增
        //serviceProvideDTO.setSkzh(driverSelfBank.getBankNum());// 是 银行卡号、微信或支付宝收款账号 2019-5-22 新增
        //司机钱包虚拟账户
        serviceProvideDTO.setKhrxm(hyDriver.getDriverName());//直接设置为司机名称
        serviceProvideDTO.setKhrsfzjhm(hyDriver.getIdcard());//直接设置为司机身份证号
        serviceProvideDTO.setKhyh("农业银行");
        //String bankNumber = hyDriverAccountBook.getProv() + hyDriverAccountBook.getAccNo() + hyDriverAccountBook.getLogAccNo();
        String bankNumber = hyDriverAccountBook.getAccNo() + hyDriverAccountBook.getLogAccNo();
        serviceProvideDTO.setSkzh(bankNumber);

        List imgList1 = new ArrayList();
        imgList1.add(ImageCompressUtil.compressSrcImageToBase64(sub + hyDriver.getIdcardImg(),500));
        imgList1.add(ImageCompressUtil.compressSrcImageToBase64(sub + hyDriver.getIdcardImgBack(),500));
        serviceProvideDTO.setSmrzfj(imgList1);// 是 司机认证正、反面照片（可推送身份证照片），图片尺寸见补充说明,照片要求进行 base64 转码传输,图片需要拼接成JSON数组格式："smrzfj": ["data:image/jpg;base64 ,正面证件编码 ","data:image/jpg;base6 ,反面证件编码  "

        List imgList2 = new ArrayList();
        imgList2.add(ImageCompressUtil.compressSrcImageToBase64(sub + hyDriver.getDriverImg(),500));
        if(StringUtils.isNotBlank(hyDriver.getDriverImg2())){
            imgList2.add(ImageCompressUtil.compressSrcImageToBase64(sub + hyDriver.getDriverImg2(),500));
        }

        serviceProvideDTO.setJszfj(imgList2);// 是 承运驾驶证照片, 图片尺 寸见补充说明, 照片要求 进行 base64 转码传输,图片 需要拼接成 JSON 数组格式： "jszfj": ["data:image/jpg;base64 ,编码"]

        serviceProvideDTO.setCycsbh("");// 否 车辆识别号代码,行驶证件 vin 号码 2019-7-10 说明-选填 标识
        serviceProvideDTO.setCyczzl("");// 否 总质量（数字+单位） 2019-7-10 说明-选填 标识
        serviceProvideDTO.setCyczbzl("");// 否 整备质量（数字+单位） 2019-7-10 说明-选填 标识
        serviceProvideDTO.setCycsyxz("");// 否 使用性质（填写内容 营 运、非营运） 2019-7-10 说明-选填 标识
        serviceProvideDTO.setCycfdjhm("");// 否 发动机号码 2019-7-10 说明-选填 标识
        serviceProvideDTO.setCyczcsj("");// 否 车辆注册时间 2019-7-10 说明-选填 标识

        String cycxszfj = ImageCompressUtil.compressSrcImageToBase64(sub + hyVehicle.getDrivingLicenseImg(),500);
        serviceProvideDTO.setCycxszfj(Collections.singletonList(cycxszfj));// 是 承运车辆行驶证照片,图 片尺寸见补充说明,照片要求进行 base64 转码传 输,图片需要拼接成 JSON 数组格式："cycxszfj": ["data:image/jpg;base 64,编码"]
        String cyczpfj = ImageCompressUtil.compressSrcImageToBase64(sub + hyVehicle.getVehicleImg(),500);
        serviceProvideDTO.setCyczpfj(Collections.singletonList(cyczpfj));// 是 承运车辆照片, 图片尺 寸见补充说明,照片要求 进行 base64 转码传输,图 片需要拼接成 JSON 数组 格式："cyczpfj": ["data:image/jpg;base 64,编码"]

        serviceProvideDTO.setClsyr(hyVehicle.getOwner());// 是 车辆所有人 （自然人、企业） 取行驶证上所有人内容
        serviceProvideDTO.setCycsjsyr(hyVehicle.getOwner());// 是 实际所有人 实际所有人为车主 （即个人，填写个人姓 名，应与服务方姓名，收款人姓名一致） 2019-5-22 新增
        serviceProvideDTO.setCycsyrlxfs(hyDriver.getTelephone());// 是 所有人联系方式 2019-5-22 新增

//		String regEx = "[^\u4e00-\u9fa5]+";
//		String[] term = hyVehicle.getOwner().split(regEx);
//		Integer count = 0;
//		for(int i =0; i < term.length; i ++)
//			count = count + term[i].length();
        //1挂靠 0非挂靠
        if (hyVehicle.getIzAffiliation().equals("1")) {
            String affiliationAgreement = ImageCompressUtil.compressSrcImageToBase64(sub + hyVehicle.getAffiliationAgreement(),500);
            serviceProvideDTO.setCycsfgk("是");// 是 是否挂靠车辆 （填写内容是能为： 是/否） ！！！！！ 判断标准 ： 是 ： 行驶证上所有人为 企业或车队等非个人 否 ： 行驶证上所有人为 个人
            serviceProvideDTO.setQysmgkfj(Collections.singletonList(affiliationAgreement));// 是 挂靠企业声明-车辆仅做 挂靠处理附件照片, 是/ 否要求 及 图片尺寸见 补充说明,照片要求进行 base64 转码传输,图片需 要拼接成 JSON 数组格式： "qysmgkfj": ["data:image/jpg;base 64,编码"]
            serviceProvideDTO.setCzsmgkfj("");// 是 车主声明-车辆所有人为 个人附件照片, 是/否要 求 及 图片尺寸见补充 说明,照片要求进行 base64 转码传输,图片需 要拼接成 JSON 数组格式： "czsmgkfj": ["data:image/jpg;base 64,编码"]
        } else {
            serviceProvideDTO.setCycsfgk("否");// 是 是否挂靠车辆 （填写内容是能为： 是/否） ！！！！！ 判断标准 ： 是 ： 行驶证上所有人为 企业或车队等非个人 否 ： 行驶证上所有人为 个人
            serviceProvideDTO.setCzsmgkfj(new ArrayList<>());// 是 车主声明-车辆所有人为 个人附件照片, 是/否要 求 及 图片尺寸见补充 说明,照片要求进行 base64 转码传输,图片需 要拼接成 JSON 数组格式： "czsmgkfj": ["data:image/jpg;base 64,编码"]
            serviceProvideDTO.setQysmgkfj("");// 是 挂靠企业声明-车辆仅做 挂靠处理附件照片, 是/ 否要求 及 图片尺寸见 补充说明,照片要求进行 base64 转码传输,图片需 要拼接成 JSON 数组格式： "qysmgkfj": ["data:image/jpg;base 64,编码"]
        }
        return serviceProvideDTO;
    }

    @Override
    public ApiBaseResDTO tjTaxUpload(HyDriver hyDriver) {
        ApiBaseResDTO result;
        if (hyDriver == null) {
            result = new ApiBaseResDTO();
            result.setDesc("司机数据为null");
            return result;
        }
//        if ("1".equals(hyDriver.getTjTaxUploadStatus())) {
//            result = new ApiBaseResDTO();
//            result.setDesc("该司机已经上报，请勿重复上报！");
//            return result;
//        }

//		List<HyVehicle> vehicleList = iHyVehicleService.getVehicleByDriverId(hyDriver.getId());
//		if(vehicleList.size() == 0){
//            ApiBaseResDTO apiBaseResDTO = new ApiBaseResDTO();
//            apiBaseResDTO.setDesc("车主名下无车辆!");
//            return apiBaseResDTO;
//		}
//		HyVehicle hyVehicle = vehicleList.get(0);

        List<String> vehicleIdList = iHyDriverVehicleService.getVehicleIdListByDriverId(hyDriver.getId());
        if (vehicleIdList == null || vehicleIdList.size() == 0) {
            result = new ApiBaseResDTO();
            result.setDesc("车主名下无车辆!");
            return result;
        }
        HyVehicle hyVehicle = iHyVehicleService.getById(vehicleIdList.get(0));

        /*
        HyDriverBank driverSelfBank = iHyDriverBankService.getDriverSelfBank(hyDriver.getDriverName(), hyDriver.getIdcard());
        if(driverSelfBank == null){
            result = new ApiBaseResDTO();
            result.setDesc("车主名下无本人银行卡!");
            return result;
        }

        String bankName = CheckBankCardIUtil.getBankNameByBankCode(driverSelfBank.getBankType());
        if(bankName == null){
            result = new ApiBaseResDTO();
            result.setDesc("车主开户行名称错误");
            return result;
        }
        */
        HyDriverAccountBook hyDriverAccountBook = iHyDriverAccountBookService.getAccountBookByDriverId(hyDriver.getId());
        if (hyDriverAccountBook == null) {
            result = new ApiBaseResDTO();
            result.setDesc("未获取到车主钱包账户信息!");
            return result;
        }
        ServiceProvideDTO serviceProvideDTO = driver2ServiceProvideDTO(hyDriver, hyVehicle, hyDriverAccountBook);
        result = dongjiangTaxSystemService.sendServiceProvide(serviceProvideDTO);
        int code = result !=null  && StringUtils.isNotEmpty(result.getCode()) ? Integer.parseInt(result.getCode()) : 0;

        hyDriver.setTjTaxUploadStatus(code >= 100 && code < 200 ? "1" : "2");
        hyDriver.setTjTaxUploadTime(new Date());
        updateById(hyDriver);

        return result;
    }

    @Override
    public ApiBaseResDTO tjTaxUpload(HyDriver hyDriver,HyVehicle hyVehicle) {
        ApiBaseResDTO result;
        if (hyDriver == null) {
            result = new ApiBaseResDTO();
            result.setDesc("司机数据为null");
            return result;
        }
        if(hyVehicle == null){
            result = new ApiBaseResDTO();
            result.setDesc("车辆数据为null");
            return result;
        }
//        if ("1".equals(hyDriver.getTjTaxUploadStatus())) {
//            result = new ApiBaseResDTO();
//            result.setDesc("该司机已经上报，请勿重复上报！");
//            return result;
//        }
        HyDriverAccountBook hyDriverAccountBook = iHyDriverAccountBookService.getAccountBookByDriverId(hyDriver.getId());
        if (hyDriverAccountBook == null) {
            result = new ApiBaseResDTO();
            result.setDesc("未获取到车主钱包账户信息!");
            return result;
        }
        ServiceProvideDTO serviceProvideDTO = driver2ServiceProvideDTO(hyDriver, hyVehicle, hyDriverAccountBook);
        result = dongjiangTaxSystemService.sendServiceProvide(serviceProvideDTO);
        int code = result !=null  && StringUtils.isNotEmpty(result.getCode()) ? Integer.parseInt(result.getCode()) : 0;

        hyDriver.setTjTaxUploadStatus(code >= 100 && code < 200 ? "1" : "2");
        hyDriver.setTjTaxUploadTime(new Date());
        updateById(hyDriver);

        return result;
    }

    @Override
    public IPage<HyDriverVehicleVO> getDriverVehiclePageList(Page<HyDriverVehicleVO> page, QueryWrapper<HyDriverVehicleVO> queryWrapper) {
        return page.setRecords(baseMapper.getDriverVehiclePageList(page, queryWrapper));
    }

    /**
     * 司机用户
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public IPage<DriverUserDTO> getDriverUserPageList(Page<DriverUserDTO> page, QueryWrapper<DriverUserDTO> queryWrapper) {
        return page.setRecords(baseMapper.getDriverUserPageList(page, queryWrapper));
    }

    @Override
    public IPage<HyDriverDTO> pageList(Page<HyDriverDTO> page, QueryWrapper<HyDriverDTO> queryWrapper,String customerId) {
        return page.setRecords(baseMapper.pageList(page, queryWrapper,customerId));
    }

    /**
     * 司机端--修改手机
     * @param driver
     * @param newPhone
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> modifyPhone(HyDriver driver, String newPhone) {
        String userId = driver.getUserId();
        SysUser user = sysUserService.getById(userId);
        if(user == null){
            return Result.error("用户信息不存在");
        }
        //检查手机号是否已存在
        int count = sysUserService.count(new QueryWrapper<SysUser>()
                .eq("phone", newPhone)
                .ne("id", userId));
        if(count > 0){
            return Result.error("手机号已被占用");
        }
        user.setPhone(newPhone);
        sysUserService.updateById(user);

        driver.setTelephone(newPhone);
        this.updateById(driver);

        return  Result.OK("修改成功!");
    }



    /**
     * 司机上报道达
     *
     * @param hyDriver
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean uploadDaoda(HyDriver hyDriver) {
        HyDriver hyDriverDb = getById(hyDriver.getId());
        if (hyDriverDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        if (hyDriverDb.getDaodaUploadStatus().equals("1")) {
            throw new JeecgBootException("该数据已上报过，请勿重复上报！");
        }
        String userID = getDaodaUserId(hyDriverDb);
        AddUserDriverDTO adduserDriverDTO = new AddUserDriverDTO();
        adduserDriverDTO.setUserID(userID);
        adduserDriverDTO.setFullname(hyDriverDb.getDriverName());
        adduserDriverDTO.setBirthDate(
                DateUtils.date2Str(hyDriverDb.getBirthday(), DateUtils.date_sdf.get())
        );
        adduserDriverDTO.setIDnumber(hyDriverDb.getIdcard());
//        if(hyDriverDb.getIdcardValidFrom() == null){
//            throw new JeecgBootException("该司机身份证有效开始日期为空，请补充信息！");
//        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(hyDriverDb.getIdcardExpiredDate());
        cal.add(Calendar.YEAR, -20);
        Date idcardValidFrom = cal.getTime();
        adduserDriverDTO.setStartExpired(
                hyDriverDb.getIdcardValidFrom() != null ?
                        DateUtils.date2Str(hyDriverDb.getIdcardValidFrom(), DateUtils.date_sdf.get()) :
                        DateUtils.date2Str(idcardValidFrom, DateUtils.date_sdf.get())
        );
        adduserDriverDTO.setEndExpired(
                DateUtils.date2Str(hyDriverDb.getIdcardExpiredDate(), DateUtils.date_sdf.get())
        );
        String idcardImg = daodaService.uploadFiles(hyDriverDb.getIdcardImg());
        adduserDriverDTO.setFrontThumb(idcardImg);
        adduserDriverDTO.setEmblemThumb(
                daodaService.uploadFiles(hyDriverDb.getIdcardImgBack())
        );
        adduserDriverDTO.setDriversThumb(
                daodaService.uploadFiles(hyDriverDb.getDriverImg())
        );
        String qualificationImg = StringUtils.isNotBlank(hyDriverDb.getQualificationImg() ) ? hyDriverDb.getQualificationImg() :hyDriverDb.getIdcardImg();
        adduserDriverDTO.setEmploymentThumb(qualificationImg);
        String reportResult = daodaService.AdduserDriver(adduserDriverDTO);
        if (StringUtils.isNotEmpty(reportResult)) {
            JSONObject jsonObject = JSONObject.parseObject(reportResult);
            boolean success = jsonObject.getBoolean("success") != null ? jsonObject.getBoolean("success") : false;
            String resultMsg = jsonObject.getString("ResultMsg") != null  ? jsonObject.getString("ResultMsg") :StringUtils.EMPTY;

            hyDriverDb.setDaodaUploadStatus(success ? "1" : "2");
            hyDriverDb.setDaodaUploadTime(new Date());
            hyDriverDb.setDaodaFailureReason(resultMsg);
            updateById(hyDriverDb);
            if (!success) {
                throw new JeecgBootException(resultMsg);
            }
            return success ? true : false;
        }
        return false;
    }

    private String getDaodaUserId(HyDriver hyDriver) {

        LambdaQueryWrapper<HyDaodaUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HyDaodaUser::getDriverId, hyDriver.getId());
        HyDaodaUser daodaUser = hyDaodaUserService.getOne(queryWrapper);

        String userID = StringUtils.EMPTY;
        if (daodaUser == null) {
            AddUserDTO addUserDTO = new AddUserDTO();
            addUserDTO.setUserName(hyDriver.getTelephone());
            addUserDTO.setPassword(hyDriver.getTelephone());
            addUserDTO.setNickname(hyDriver.getDriverName());
            String addUser = daodaService.AddUser(addUserDTO);
            if (StringUtils.isEmpty(addUser)) {
                throw new JeecgBootException("司机用户推送失败！");
            }
            JSONObject addUserJsonObject = JSONObject.parseObject(addUser);
            userID = addUserJsonObject.getString("UserID");
            hyDaodaUserService.save(new HyDaodaUser().setDriverId(hyDriver.getId()).setUserId(userID));
        } else {
            userID = daodaUser.getUserId();
        }

        return userID;
    }


    /**
     * 辽宁税务税登
     * @param ids
     * @return
     */
    @Override
    public Result lnTaxedDriver(String ids) {

        if (StrUtil.isEmpty(ids)) {
            return Result.error("请选择司机！");
        }

        List<String> driverIds = Arrays.asList(ids.split(","));
        int driverCount = this.count(new LambdaQueryWrapper<HyDriver>().in(HyDriver::getId, driverIds));
        if (driverCount != driverIds.size()) {
            return Result.error("所选司机数据存在错误");
        }

        AlctApiBaseResDTO resDTO = oapiAlct56Service.submitTaxpayer(driverIds);
        if (!resDTO.getCode().equals("0")) {
            return Result.error(resDTO.getMessage());
        }

        return Result.OK();
    }


    //辽宁税务上报司机信息
    @Override
    public Result<?> lnTaxUploadDriver(HyDriver hyDriver) {

        if (null == hyDriver.getIdcardValidFrom()) {
            return Result.error("该司机身份证有效期起始时间不能为空");
        }

        if (null == hyDriver.getIdcardExpiredDate()) {
            return Result.error("该司机身份证有效期截止时间不能为空");
        }

        if (hyDriver.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyDriver.getLnTaxUploadStatus().split("\\|");
            if (uploadStatus[0].equals("1")){
                return Result.error("该司机信息已上报过，请勿重复上报！");
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");

        org.jeecg.modules.third.oapi.alct56.dto.req.driver.DriverDTO driverDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.DriverDTO();
        driverDTO.setDriverName(hyDriver.getDriverName());
        driverDTO.setMobile(hyDriver.getTelephone());
        driverDTO.setSendActivationSms(false);

        org.jeecg.modules.third.oapi.alct56.dto.req.driver.Identity identity = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.Identity();
        identity.setIdentityNo(hyDriver.getIdcard());
        identity.setEffectiveStartDate(format.format(hyDriver.getIdcardValidFrom()));
        String endDate = format.format(hyDriver.getIdcardExpiredDate());
        identity.setEffectiveEndDate(endDate);
        if (endDate.equals("9999-12-30")) {
            identity.setIsEndless(true);
        } else {
            identity.setIsEndless(false);
        }

//        try{
//            //要识别身份证有效期自
//            String idcradJsonS = aliyunOcrService.ocrIdcard(uploadpath + File.separator + hyDriver.getIdcardImgBack(), "back");
//            JSONObject idcradJsonO = JSONObject.parseObject(idcradJsonS);
//            //身份证有效期自
//            String start_date = idcradJsonO.getString("start_date");
//            Date startDate = format1.parse(start_date);
//            identity.setEffectiveStartDate(format.format(startDate));
//            if(idcradJsonO.getString("end_date").equals("长期")){
//                identity.setIsEndless(true);
//            }else{
//                String end_date = idcradJsonO.getString("end_date");
//                Date endDate = format1.parse(end_date);
//                identity.setEffectiveEndDate(format.format(endDate));
//            }
//        }catch (Exception ex){
//            throw new JeecgBootException("身份证有效期转换错误！" + ex.getMessage());
//        }
        org.jeecg.modules.third.oapi.alct56.dto.req.driver.DrivingLicense drivingLicense = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.DrivingLicense();
        drivingLicense.setLicenseNo(hyDriver.getDrivingLicense());//驾驶证号 是
        if (ObjectUtil.isEmpty(hyDriver.getIssueStartDate())) {
            return Result.error("该司机驾驶证初次领证日期不能为空！");
        }
        drivingLicense.setLicenseFirstGetDate(format.format(hyDriver.getIssueStartDate()));//首次驾照签发日期 是
//        try {
//            //识别驾驶证首次签发日期
//            String httpUri = huaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE);
//            String drivingLicenseJsonS = huaweiOcrService.getInfoByToken(uploadpath + File.separator + hyDriver.getDriverImg(), httpUri, "front");
//            JSONObject drivingLicenseJsonO = JSONObject.parseObject(drivingLicenseJsonS);
//            drivingLicense.setLicenseFirstGetDate(drivingLicenseJsonO.getString("issue_date"));//首次驾照签发日期 是
//        }catch (Exception ex){
//            throw new JeecgBootException("识别驾驶证失败！" + ex.getMessage());
//        }
        drivingLicense.setLicenseType(hyDriver.getVehicleClass());//驾驶证类型 是
        drivingLicense.setEffectiveStartDate(format.format(hyDriver.getValidPeriodFrom()));//有效期开始日期 是
        drivingLicense.setEffectiveEndDate(format.format(hyDriver.getValidPeriodTo()));//有效期结束 是
        drivingLicense.setApproveOrganization(hyDriver.getIssuingOrganizations());//驾驶证发证机关 否
        //必须传 开票要用
        org.jeecg.modules.third.oapi.alct56.dto.req.driver.Taxpayer taxpayer = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.Taxpayer();
        taxpayer.setTaxpayerName(hyDriver.getDriverName());//	名称 否
        taxpayer.setTaxpayerIdentityNo(hyDriver.getIdcard());//	身份证号码 否
        taxpayer.setTaxpayerAddress(hyDriver.getAddress());//	身份证地址 否
        taxpayer.setTaxpayerMobile(hyDriver.getTelephone());//	纳税人手机号 否
        //获取司机绑定的本人银行卡
        HyDriverBank driverSelfBank = iHyDriverBankService.getDriverSelfBank(hyDriver.getId());
        if (driverSelfBank == null) {
            return Result.error("司机未绑定本人银行卡!");
        }
        String bankName = BankTypeUtil.getBankNameByBankType(driverSelfBank.getBankType());
        taxpayer.setBankName(bankName);//	开户行名称 否
        taxpayer.setBankAccount(driverSelfBank.getBankNum());//	账号 否

        driverDTO.setIdentity(identity);
        driverDTO.setDrivingLicense(drivingLicense);
        driverDTO.setTaxpayer(taxpayer);

        log.warn("上传辽宁税务-司机信息, {}", JSONUtil.toJsonStr(driverDTO));
        //上传司机信息
        AlctApiBaseResDTO resDTO = oapiAlct56Service.submitDriver(driverDTO);
        log.warn("辽宁税务返回-司机信息, {}", JSONUtil.toJsonStr(resDTO));
        if (resDTO.getMessage().contains("已存在")) {
            return Result.OK("辽宁税务：司机信息已存在！");
        }

        boolean isSuccess = false;
        String status;
        if (resDTO.getCode().equals("0")) {
            isSuccess = true;
            hyDriver.setLnTaxUploadStatus("1");
        } else {
            isSuccess = false;
            hyDriver.setLnTaxUploadStatus("2");
        }
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        hyDriver.setLnTaxUploadTime(format2.format(new Date()));
        this.updateById(hyDriver);
        return isSuccess ? Result.OK("辽宁税务：司机信息上报成功！") : Result.error(resDTO.getMessage());
    }

    @Override
    public Result<?> updatelnTaxUploadDriver(HyDriver hyDriver) {
        AlctApiBaseResDTO result = oapiAlct56Service.getDriverStatus("/api/v1/openapi/drivers?identityNo=", hyDriver.getIdcard());
        log.info("查询司机状态, {}", JSONUtil.toJsonStr(result));
        if (!"0".equals(result.getCode())) {
            return Result.error(result.getMessage());
        }

        cn.hutool.json.JSONObject json = JSONUtil.parseObj(result.getDriver());
        if ("已税登".equals(json.getStr("taxRegisterStatusDescription"))) {
            return Result.error("该司机已完成税登，不能更新信息");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        org.jeecg.modules.third.oapi.alct56.dto.req.driver.DriverDTO driverDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.DriverDTO();
        driverDTO.setDriverName(hyDriver.getDriverName());
        driverDTO.setMobile(hyDriver.getTelephone());
        driverDTO.setSendActivationSms(false);

        //请不要随意更新司机的身份证号码，如果身份证错误，系统会直接创建新司机。当司机已经税务登记后，则司机的信息更新请求会被忽略。
        org.jeecg.modules.third.oapi.alct56.dto.req.driver.Identity identity = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.Identity();
        identity.setIdentityNo(hyDriver.getIdcard());
        identity.setEffectiveStartDate(format.format(hyDriver.getIdcardValidFrom()));
        String endDate = format.format(hyDriver.getIdcardExpiredDate());
        identity.setEffectiveEndDate(endDate);
        if (endDate.equals("9999-12-30")) {
            identity.setIsEndless(true);
        } else {
            identity.setIsEndless(false);
        }

        org.jeecg.modules.third.oapi.alct56.dto.req.driver.DrivingLicense drivingLicense = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.DrivingLicense();
        drivingLicense.setLicenseNo(hyDriver.getDrivingLicense());//驾驶证号 是
        if (ObjectUtil.isEmpty(hyDriver.getIssueStartDate())) {
            return Result.error("该司机驾驶证初次领证日期不能为空！");
        }
        drivingLicense.setLicenseFirstGetDate(format.format(hyDriver.getIssueStartDate()));//首次驾照签发日期 是
        drivingLicense.setLicenseType(hyDriver.getVehicleClass());//驾驶证类型 是
        drivingLicense.setEffectiveStartDate(format.format(hyDriver.getValidPeriodFrom()));//有效期开始日期 是
        drivingLicense.setEffectiveEndDate(format.format(hyDriver.getValidPeriodTo()));//有效期结束 是
        drivingLicense.setApproveOrganization(hyDriver.getIssuingOrganizations());//驾驶证发证机关 否
        //必须传 开票要用
        org.jeecg.modules.third.oapi.alct56.dto.req.driver.Taxpayer taxpayer = new org.jeecg.modules.third.oapi.alct56.dto.req.driver.Taxpayer();
        taxpayer.setTaxpayerName(hyDriver.getDriverName());//	名称 否
        taxpayer.setTaxpayerIdentityNo(hyDriver.getIdcard());//	身份证号码 否
        taxpayer.setTaxpayerAddress(hyDriver.getAddress());//	身份证地址 否
        taxpayer.setTaxpayerMobile(hyDriver.getTelephone());//	纳税人手机号 否
        //获取司机绑定的本人银行卡
        HyDriverBank driverSelfBank = iHyDriverBankService.getDriverSelfBank(hyDriver.getId());
        if (driverSelfBank == null) {
            return Result.error("司机未绑定本人银行卡!");
        }
        String bankName = BankTypeUtil.getBankNameByBankType(driverSelfBank.getBankType());
        taxpayer.setBankName(bankName);//	开户行名称 否
        taxpayer.setBankAccount(driverSelfBank.getBankNum());//	账号 否

        driverDTO.setIdentity(identity);
        driverDTO.setDrivingLicense(drivingLicense);
        driverDTO.setTaxpayer(taxpayer);

        log.warn("上传辽宁税务-更新司机信息, {}", JSONUtil.toJsonStr(driverDTO));
        //更新司机信息
        AlctApiBaseResDTO resDTO = oapiAlct56Service.put("/api/v1/openapi/drivers", driverDTO);
        log.warn("辽宁税务返回-更新司机信息, {}", JSONUtil.toJsonStr(resDTO));
        if (!"0".equals(resDTO.getCode())) {
            return Result.error(resDTO.getMessage());
        }

        return Result.OK("操作成功");
    }

    //辽宁税务上传照片
    private AlctApiBaseResDTO lnTaxUploadImg(String idcradNo, Map<String, String> imgMap) {
        org.jeecg.modules.third.oapi.alct56.dto.req.image.ImageDTO imageDTO = new org.jeecg.modules.third.oapi.alct56.dto.req.image.ImageDTO();
        imageDTO.setIdentityNo(idcradNo);//身份证号
        imageDTO.setImageCategory(ImageCategory.Driver.getValue());//照片种类
        imageDTO.setImageType(imgMap.get("imageType"));//照片类型
        String img = imgMap.get("img");
        if (StrUtil.isEmpty(img)) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            return resDTO;
            //throw new JeecgBootException("当前司机(" + imgMap.get("imgInfo") + ")照片未找到");
        }

        //img如果没有后缀，按照异常文件处理
        if ( -1 == img.indexOf(".jp") && -1 == img.indexOf(".png")) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            return resDTO;
        }

        imageDTO.setFileExt(img.substring(img.lastIndexOf("."), img.length()));//文件类型
        String base64Str = ImageCompressUtil.compressSrcImageToBase64(img,500);
        if (StrUtil.isEmpty(base64Str)) {
            AlctApiBaseResDTO resDTO = new AlctApiBaseResDTO();
            resDTO.setCode("1");
            resDTO.setMessage("照片未找到");
            return resDTO;
        }
        imageDTO.setFileData(base64Str);//照片base64串
        //上报结果
        return oapiAlct56Service.submitImage(imageDTO);
    }

    //辽宁税务上报司机所需照片(身份证正面、身份证反面、驾驶证、【从业资格证】、司机纳税人身份证正面、司机纳税人银行卡正面)
    //index：-1上报所有照片 0-5上报对应单独照片
    @Override
    public Result<?> lnTaxUploadDriverImg(HyDriver hyDriver, int index) {
        //图片List
        List<Map<String, String>> imgList = new ArrayList<>();
        //身份证正面 带国徽面
        Map<String, String> sfzzmImgMap = new HashMap<>();
        sfzzmImgMap.put("imageType", ImageType.IdentityFront.getValue());
        sfzzmImgMap.put("imgInfo", ImageType.IdentityFront.getMsg());
        sfzzmImgMap.put("img", uploadpath + File.separator + hyDriver.getIdcardImgBack());
        //身份证反面 带人头面
        Map<String, String> dsfzfmImgMap = new HashMap<>();
        dsfzfmImgMap.put("imageType", ImageType.IdentityBack.getValue());
        dsfzfmImgMap.put("imgInfo", ImageType.IdentityBack.getMsg());
        dsfzfmImgMap.put("img", uploadpath + File.separator + hyDriver.getIdcardImg());
        //驾驶证
        Map<String, String> jszImgMap = new HashMap<>();
        jszImgMap.put("imageType", ImageType.DrivingLicense.getValue());
        jszImgMap.put("imgInfo", ImageType.DrivingLicense.getMsg());
        jszImgMap.put("img", uploadpath + File.separator + hyDriver.getDriverImg());
        //【从业资格证】
        Map<String, String> cyzgzImgMap = new HashMap<>();
        cyzgzImgMap.put("imageType", ImageType.QualificationCertificate.getValue());
        cyzgzImgMap.put("imgInfo", ImageType.QualificationCertificate.getMsg());
        if (hyDriver.getQualificationImg() == null) {
            //没有从业资格证证照片 先用驾驶证照片传上
            cyzgzImgMap.put("img", uploadpath + File.separator + hyDriver.getDriverImg());
        } else {
            cyzgzImgMap.put("img", uploadpath + File.separator + hyDriver.getQualificationImg());
        }
        //司机纳税人身份证正面 带人头面
        Map<String, String> nsrsfzzmImgMap = new HashMap<>();
        nsrsfzzmImgMap.put("imageType", ImageType.TaxpayerIdentity.getValue());
        nsrsfzzmImgMap.put("imgInfo", ImageType.TaxpayerIdentity.getMsg());
        nsrsfzzmImgMap.put("img", uploadpath + File.separator + hyDriver.getIdcardImg());

        //司机纳税人银行卡正面
        Map<String, String> nsryhkzmImgMap = new HashMap<>();
        HyDriverBank driverSelfBank = iHyDriverBankService.getDriverSelfBank(hyDriver.getId());
        if (driverSelfBank == null) {
            return Result.error("司机未绑定本人银行卡，无法上传银行卡照片！");
        } else {
            nsryhkzmImgMap.put("imageType", ImageType.TaxpayerBankCard.getValue());
            nsryhkzmImgMap.put("imgInfo", ImageType.TaxpayerBankCard.getMsg());
            nsryhkzmImgMap.put("img", uploadpath + File.separator + driverSelfBank.getBankImgFront());
        }

        imgList.add(sfzzmImgMap);
        imgList.add(dsfzfmImgMap);
        imgList.add(jszImgMap);
        imgList.add(cyzgzImgMap);
        imgList.add(nsrsfzzmImgMap);
        imgList.add(nsryhkzmImgMap);

        log.info("辽宁税务上报司机信息, {} {} {}", hyDriver.getDriverName(), index, JSONUtil.toJsonStr(imgList));

        //循环上报
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String errorMsg = "";
        if (index == -1) {
            String uploadStatus = "";
            String uploadTime = "";

            for (int i = 0; i < imgList.size(); i++) {
                Map<String, String> imgMap = imgList.get(i);
                //上报结果
                AlctApiBaseResDTO resDTO = lnTaxUploadImg(hyDriver.getIdcard(), imgMap);
                if (resDTO.getCode().equals("0")) {
                    uploadStatus += "|1";//上报成功
                } else {
                    uploadStatus += "|2";//上报失败
                    errorMsg += imgMap.get("imgInfo") + "上报失败：" + resDTO.getMessage() + "！";
                }
                //记录上报时间
                Date now = new Date();
                uploadTime += "|" + format.format(now);
            }
            hyDriver.setLnTaxUploadStatus(hyDriver.getLnTaxUploadStatus() + uploadStatus);
            hyDriver.setLnTaxUploadTime(hyDriver.getLnTaxUploadTime() + uploadTime);
        } else {
            String[] uploadStatus = hyDriver.getLnTaxUploadStatus().split("\\|");
            String[] uploadTime = hyDriver.getLnTaxUploadTime().split("\\|");
            AlctApiBaseResDTO resDTO = lnTaxUploadImg(hyDriver.getIdcard(), imgList.get(index));
            if (resDTO.getCode().equals("0")) {
                uploadStatus[index + 1] = "1";//上报成功
            } else {
                uploadStatus[index + 1] = "2";//上报失败
                errorMsg = resDTO.getMessage();
            }
            //记录上报时间
            Date now = new Date();
            uploadTime[index + 1] = format.format(now);

            hyDriver.setLnTaxUploadStatus(String.join("|", uploadStatus));
            hyDriver.setLnTaxUploadTime(String.join("|", uploadTime));
        }
        this.updateById(hyDriver);
        return errorMsg.equals("") ? Result.OK("上报成功！") : Result.error(errorMsg);
    }

    //辽宁税务上报司机所有信息
    @Override
    public Result<?> lnTaxUploadDriverAll(HyDriver hyDriver) {
        if (hyDriver.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyDriver.getLnTaxUploadStatus().split("\\|");
            if (uploadStatus[0].equals("1")) {
                //检测司机信息已上报过，就不再调用司机信息上报接口
                Result imgRes = lnTaxUploadDriverImg(hyDriver, -1);
                return imgRes.isSuccess() ? Result.OK("上报成功！") : Result.error(imgRes.getMessage());
            }
        }
        Result driverRes = lnTaxUploadDriver(hyDriver);
        //司机未上报成功时不去调用其它上报接口
        if (!driverRes.isSuccess()) {
            return Result.error("司机信息上报失败：" + driverRes.getMessage() + "！");
        }

        Result imgRes = lnTaxUploadDriverImg(hyDriver, -1);
        return imgRes.isSuccess() ? Result.OK("上报成功！") : Result.error(imgRes.getMessage());
    }

    //获取司机辽宁税务是否登记成功
    @Override
    public boolean izDriverLnUploadSuccess(HyDriver hyDriver) {
        if (hyDriver.getLnTaxUploadStatus() != null) {
            String[] uploadStatus = hyDriver.getLnTaxUploadStatus().split("\\|");
            if (uploadStatus[0].equals("1")) {
                return true;
            }
        }
        return false;
    }


    //快货运上报
    //上报承运人(用司机信息)
    @Override
    public Result<?> tosUploadCarrier(HyDriver hyDriver) {
        CarrierDTO carrierDTO = new CarrierDTO();
        carrierDTO.setEnterprise_flag(YNEnum.NO.getCode());//	是否是企业	是		enum (NO, YES)
        carrierDTO.setName(hyDriver.getDriverName());//	实际承运人名称	是	an..256	与网络货运经营者签订运输合同，实际完成运输的经营者。取得道路运输经营许可证的运输业户，直接填写“许可证上的业户名称”；其他情况填写“运输公司名称（合同签订人姓名）”。

        //找到司机名下车辆，取得车籍地地址
        List<String> vehicleIdList = iHyDriverVehicleService.getVehicleIdListByDriverId(hyDriver.getId());
        if (vehicleIdList == null || vehicleIdList.size() == 0) {
            return Result.error("承运人名下无车辆，无法上报注册地（行驶证住址）信息!");
        }
        HyVehicle hyVehicle = iHyVehicleService.getById(vehicleIdList.get(0));
        carrierDTO.setActual_carrier_register_address(hyVehicle.getVehicleAddress());//	实际承运人信息-注册地	是	an..512	如果为个体司机，注册地按营运车辆车籍地填写
//        carrierDTO.setActual_carrier_audit_time("");//	实际承运人信息-通过平台审核日期	否	n13	13 位毫秒时间戳。eg：1577811661000

        carrierDTO.setPhone(hyDriver.getTelephone());//	企业联系人手机号或者个人手机号	是	an..18
        carrierDTO.setIdentity(hyDriver.getIdcard());//	个人身份证号	个人必填	an..18
        carrierDTO.setIdentity_frontal_pic(tosApiService.uploadFile(hyDriver.getIdcardImg()));//	身份证正面照图片 URL	个人必填	an..1024	文件上传接口返回地址
        carrierDTO.setIdentity_reverse_pic(tosApiService.uploadFile(hyDriver.getIdcardImgBack()));//	身份证反面照片图片 URL	个人必填	an..1024	文件上传接口返回地址

        //个人类型时，户籍地址和常驻地址个人必传一组
        carrierDTO.setHousehold_region(hyDriver.getIdcard().substring(0, 4) + "00");//	户籍地址行政区划		an..12	参考行政区划代码集
        carrierDTO.setHousehold_address(hyDriver.getAddress());//	户籍地址详细地址		an..256

        TosApiBaseResDTO resDTO = tosApiService.subjectCarrier(carrierDTO);

        hyDriver.setTosUploadCarrierTime(new Date());
        if (resDTO.isSuccess()) {
            hyDriver.setTosUploadCarrierStatus("1");
            this.updateById(hyDriver);
            return Result.OK("承运人上报成功！");
        } else {
            hyDriver.setTosUploadCarrierStatus("2");
            this.updateById(hyDriver);
            return Result.error(resDTO.getBiz_message());
        }
    }

    //上报司机
    @Override
    public Result<?> tosUploadDriver(HyDriver hyDriver) {
        org.jeecg.modules.third.tosapi.dto.driver.DriverDTO driverDTO = new org.jeecg.modules.third.tosapi.dto.driver.DriverDTO();
        driverDTO.setName(hyDriver.getDriverName());//	司机姓名	是		an..30
        driverDTO.setPhone(hyDriver.getTelephone());//	电话	是		n11
        driverDTO.setIdentity(hyDriver.getIdcard());//	司机身份证号	是		an..18
        driverDTO.setLicence(hyDriver.getDrivingLicense());//	驾驶证号	是		an..18
        driverDTO.setDriving_class(hyDriver.getVehicleClass());//	准驾车型	是	根据驾驶证填写	an..20
        driverDTO.setLicence_issuing(hyDriver.getIssuingOrganizations());//	驾驶证发证机关	是		an..30
        driverDTO.setValid_from(hyDriver.getValidPeriodFrom().getTime() + "");//	驾驶证有效期自	是	13位毫秒时间戳。eg：1577811661000。时间范围不得跨越，	n13
        driverDTO.setValid_to(hyDriver.getValidPeriodTo().getTime() + "");//	驾驶证有效期至	是	13位毫秒时间戳。eg：1577811661000；长期传2099-12-31的13位毫秒时间戳	n13
        driverDTO.setQualification_cert_no(hyDriver.getIdcard().substring(0, 6) + "000000000000");//	从业资格证号	是	无的情况下填写“驾驶员身份证前6位+000000000000	an..19
        driverDTO.setQualification_cert_class("经营性道路货物运输驾驶员");//	驾驶员信息-从业资格类别	否	广东地区必填：包含经营性道路货物运输驾驶员、道路危险货物运输驾驶员、其他、无等四类	an..50
        driverDTO.setIdentity_frontal_pic(tosApiService.uploadFile(hyDriver.getIdcardImg()));//	身份证正面照图片URL	是	文件上传接口返回的地址	an..1024
        driverDTO.setIdentity_reverse_pic(tosApiService.uploadFile(hyDriver.getIdcardImgBack()));//	身份证反面照图片URL	是	文件上传接口返回的地址	an..1024

        //户籍地址/常住地址必填一组
        driverDTO.setHousehold_region(hyDriver.getIdcard().substring(0, 4) + "00");//	户籍地址行政区划	参考代码集行政区划	code http://www.mca.gov.cn/article/sj/xzqh/2020/2020/202003301019.html
        driverDTO.setHousehold_address(hyDriver.getAddress());//	户籍地址详细地址		an..128

        driverDTO.setLicence_frontal_pic(tosApiService.uploadFile(hyDriver.getDriverImg()));//	驾驶证正面照图片URL	是	文件上传接口	an..1024

        if(StringUtils.isNotBlank(hyDriver.getDriverImg2() )){
            driverDTO.setLicence_reverse_pic(tosApiService.uploadFile(hyDriver.getDriverImg2()));//	驾驶证反面照图片URL	是	文件上传接口	an..1024
        }

        driverDTO.setApproved_time(hyDriver.getCreateTime().getTime() + "");//13位毫秒时间戳，广东地区客户必填，否则不传时上报交通取司机创建时间
        TosApiBaseResDTO resDTO = tosApiService.subjectDriver(driverDTO);

        hyDriver.setTosUploadDriverTime(new Date());
        if (resDTO.isSuccess()) {
            hyDriver.setTosUploadDriverStatus("1");
            this.updateById(hyDriver);
            return Result.OK("司机上报成功！");
        } else {
            hyDriver.setTosUploadDriverStatus("2");
            this.updateById(hyDriver);
            return Result.error(resDTO.getBiz_message());
        }
    }

    //excal表导入
/*
    @Override
    public Boolean importExcelData(MultipartFile file) {


        List<HyDriver> list = new ArrayList<>();
        HyDriver hyDriver = null;

        try {

            // 通过文件输入流读取到对应的 workbook 工作簿
            HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
            // 只解析第一张 sheet 工作表
            HSSFSheet sheet = workbook.getSheetAt(0);
            // 遍历第一个工作表的所有行
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i <= 1) continue; // 跳过标题行

                LOGGER.info("第几行",i);
                HSSFRow row = sheet.getRow(i); // 获取工作表中的某一行，通过下标获取
                if (row == null) continue; // 跳过空行

                hyDriver = new HyDriver();
                // 遍历一个行中的所有列
                for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {

                    LOGGER.info("第几列="+j);

                    HSSFCell cell = row.getCell(j); // 获取一行中的某个单元格，通过下标获取
                    if (cell == null) continue; // 跳过空单元格
                    // 获取单元格中的字符串内容
                    String cellValue = cell.getStringCellValue();
                    // 获取单元格中的数字内容
//                    double cellValue2 = cell.getNumericCellValue();
//                    String cellValue3 = Double.toString(cellValue2);
                    // 判断单元格是第几个，从零开始
                    switch (j) {
                        case 0: // 第一列机动车驾驶证
                            hyDriver.setDriverName(cellValue); // 给实体类的driverName属性赋值
                            break;
                        case 1: // 身份证号
                            hyDriver.setIdcard(cellValue);
                            break;
                        case 2: // 准驾车型

                            hyDriver.setVehicleClass(cellValue);
                            break;
                        case 3: // 驾驶证发证机关

                            hyDriver.setIssuingOrganizations(cellValue);
                            break;
                        case 4: // 出生日期
                            // 如果没有特意去定义 excel 中的日期，那么获取到的日期就是字符串类型
                            // 这里将字符串日期转换为日期格式 LocalDateTime 或 Date
                            // 1. 将日期转换为 LocalDateTime
                            // LocalDateTime time = LocalDateTime.parse(cellValue, DateTimeFormatter.ofPattern("yyyy年M月d日HH:mm:ss"));
                            // 2. 将日期转换为 Date
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日HH:mm:ss");
                            Date date = sdf.parse(cellValue);
                            hyDriver.setBirthday(date);
                            break;
                    }


                }

                list.add(hyDriver);
                // 做一下批量添加学生信息的操作即可，这里使用 MyBatis-Plus 提供的方法进行批量新增

            }

            LOGGER.info("测试一下能不能录入是"+list.toString());

//            HyDriverServiceImpl.saveBatch(list);
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("导入失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 手动回滚代码
            return false;

        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }

    }
*/

    /**
     * 彻底删除司机信息  慎用
     * @param id
     * @return
     */
    @Override
    public  int deleteDriverById(String id){
        return hyDriverMapper.deleteDriverById( id);
    }
    @Override
    public  HyDriver getDriverById(String id){
        return hyDriverMapper.getDriverById( id);
    }


    //excal表导入

    @Override
    @Transactional
    public void saveBatchDriver(List<ImportHyDriverDTO> listDriver){
        //保存用户
        SysDepart sysDepart = departService.getSysDepartById(driverDepartpid);
        List<SysUser> sysUsers  = listDriver.stream().map(
                item -> ImportHyDriverDTOTOSysUser(item,sysDepart)
        ).collect(Collectors.toList());

        sysUserService.saveBatch(sysUsers);
        //保存用户部门和角色
        List<SysUserRole> userRoles = new ArrayList();
        List<SysUserDepart> userDeaprts = new ArrayList();
        HashMap<String, String> userIDMap = new HashMap<>();

        for(SysUser user :sysUsers){
            SysUserDepart userDeaprt = new SysUserDepart(user.getId(), sysDepart.getId());
            SysUserRole userRole = new SysUserRole(user.getId(), driverRoleID);
            userRoles.add(userRole);
            userDeaprts.add(userDeaprt);
            userIDMap.put(user.getPhone(),user.getId());
        }
        sysUserRoleService.saveBatch(userRoles) ;
        sysUserDepartService.saveBatch(userDeaprts);

        //保存司机
        List<HyDriver> hyDrivers  = listDriver.stream().map(
                item -> ImportImportHyDriverDTOTOHyDriver(item ,userIDMap.get(item.getTelephone()))
        ).collect(Collectors.toList());
        this.saveBatch(hyDrivers);

        //关联车辆
        for (ImportHyDriverDTO dto : listDriver) {
            if (StrUtil.isEmpty(dto.getVehicleNumber()) || StrUtil.isEmpty(dto.getVehicleNumber().trim())) {
                continue;
            }

            HyVehicle vehicle = this.iHyVehicleService.getHyVehicleByVehicleNumber(dto.getVehicleNumber());
            if (null == vehicle) {
                log.warn("车辆不存在，忽略此关联车牌：{}", dto.getVehicleNumber());
                continue;
            }

            List<HyDriver> hyDriverList = this.list(new LambdaQueryWrapper<HyDriver>().eq(HyDriver::getDrivingLicense, dto.getDrivingLicense()));
            if (CollUtil.isEmpty(hyDriverList)) {
                log.warn("司机不存在或未入库, {} - {}", dto.getDriverName(), dto.getDrivingLicense());
                continue;
            }

            HyDriver hyDriver = hyDriverList.get(0);
            this.iHyVehicleService.update(new LambdaUpdateWrapper<HyVehicle>()
                    .eq(HyVehicle::getId, vehicle.getId())
                    .set(HyVehicle::getDriverId, hyDriver.getId())
            );

            HyDriverVehicle hyDriverVehicle = new HyDriverVehicle();
            hyDriverVehicle.setDriverId(hyDriver.getId());
            hyDriverVehicle.setVehicleId(vehicle.getId());
            hyDriverVehicle.setIzUsed(1);
            this.hyDriverVehicleService.saveOrUpdate(hyDriverVehicle);
        }
    }

    @Override
    @Transactional
    public void saveBatchDriver2(List<ImportFWFHyDriverDTO> listDriver){

        List<HyDriver> driverList =new ArrayList<>();
        for (ImportFWFHyDriverDTO importFWFHyDriverDTO : listDriver) {
            importFWFHyDriverDTO.getFwfsfzjhm();
            HyDriver driver = this.getOne(new QueryWrapper<HyDriver>().eq("idcard",importFWFHyDriverDTO.getFwfsfzjhm()));
            if(driver!=null){
                driver.setFwfuuid(importFWFHyDriverDTO.getFWFUUID());
                driverList.add(driver);
            }
        }
        this.updateBatchById(driverList);

    }

    @Override
    public HyDriver getbyIdForUpdate(String driverId) {
        return baseMapper.selectByIdForUpdate(driverId);
    }

    @Override
    public List<HyVehicle> getDriverVehicleList(String driverID) {
        return baseMapper.getDriverVehicleList(driverID);
    }

    @Override
    public int getDsDriverCount(String customerId) {

        return baseMapper.getDsDriverCount(customerId);
    }

    @Override
    public Result<?> checkVehicleOverdueTime(HyDriver driver,HyVehicle vehicle) {

        if(vehicle!=null){
            if(vehicle.getRoadTransportExpiredDate()!=null){
                if(!vehicle.getRoadTransportExpiredDate().after(new Date())){
                    return Result.error(-4,"车辆道路运输证已过期,不允许接单");
                }
            }
        }
        if(driver!=null){
            if(driver.getValidPeriodTo()!=null){
                if(!driver.getValidPeriodTo().after(new Date())){
                    return Result.error(-3,"司机驾驶证已过期,不允许接单");
                }
            }
            if(driver.getQualificationExpiredDate()!=null){
                if(!driver.getQualificationExpiredDate().after(new Date())){
                    return Result.error(-3,"司机从业资格证已过期,不允许接单");
                }
            }
        }
        return Result.OK();
    }

    @Override
    public IPage<HySelectDriverDTO> getSelectPageList(Page<HySelectDriverDTO> page, QueryWrapper<HyDriver> queryWrapper) {
        return baseMapper.getSelectPageList(page,queryWrapper);
    }

    @Override
    public boolean checkIsDriverVehicle(String driverId, String vehicleId) {
        int count = iHyDriverVehicleService.count(new QueryWrapper<HyDriverVehicle>().eq("driver_id",driverId).eq("vehicle_id",vehicleId));
        return count > 0;
    }

    @Override
    public IPage<HySelectDriverDTO> getMultipleSelectPageList(Page<HySelectDriverDTO> page, QueryWrapper<HyDriver> queryWrapper) {
        return baseMapper.getMultipleSelectPageList(page,queryWrapper);
    }

    @Override
    public boolean updateJgUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getUploadDate, new Date())
                .set(HyDriver::getUploadStatus, status));
    }

    @Override
    public boolean updateSxUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getSxUploadDate, new Date())
                .set(HyDriver::getSxUploadStatus, status));
    }

    @Override
    public boolean updateAhUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getAhUploadDate, new Date())
                .set(HyDriver::getAhUploadStatus, status));
    }

    @Override
    public boolean updateHbUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getHbUploadDate, new Date())
                .set(HyDriver::getHbUploadStatus, status));
    }

    @Override
    public boolean updateYqUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getXzUploadDate, new Date())
                .set(HyDriver::getXzUploadStatus, status));
    }

    @Override
    public boolean updateJxUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getJxUploadDate, new Date())
                .set(HyDriver::getJxUploadStatus, status));
    }

    @Override
    public boolean updateJsUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getJsUploadDate, new Date())
                .set(HyDriver::getJsUploadStatus, status));
    }

    @Override
    public boolean updateZjUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getZjUploadDate, new Date())
                .set(HyDriver::getZjUploadStatus, status));
    }

    @Override
    public boolean updateHubeiUploadStatusById(String id, String status) {
        return this.update(new LambdaUpdateWrapper<HyDriver>().eq(HyDriver::getId, id)
                .set(HyDriver::getHubeiUploadDate, new Date())
                .set(HyDriver::getHubeiUploadStatus, status));
    }

    private  SysUser ImportHyDriverDTOTOSysUser(ImportHyDriverDTO importHyDriverDTO ,SysDepart sysDepart){
        if (importHyDriverDTO == null) {
            return null;
        }
        SysUser user = new SysUser();
        String phone = importHyDriverDTO.getTelephone();
        user.setCreateTime(new Date());
        user.setUsername(phone);
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        //设置默认密码123456
        user.setPassword("Aa.123456");
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setRealname(importHyDriverDTO.getDriverName());
        user.setPhone(phone);
        user.setActivitiSync(CommonConstant.ACT_SYNC_0);
        user.setOrgCode(sysDepart.getOrgCode());
        user.setStatus(CommonConstant.USER_UNFREEZE);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setCreateBy("管理员");
        user.setUType("4");

        return  user;
    }


    private HyDriver ImportImportHyDriverDTOTOHyDriver(ImportHyDriverDTO importHyDriverDTO ,String userId) {
        if (importHyDriverDTO == null) {
            return null;
        }
        HyDriver hyDriver = new HyDriver();
        hyDriver.setDriverName(importHyDriverDTO.getDriverName());
        hyDriver.setIdcard(importHyDriverDTO.getDrivingLicense());
        hyDriver.setVehicleClass(importHyDriverDTO.getVehicleClass());
        hyDriver.setIssuingOrganizations(importHyDriverDTO.getIssuingOrganizations());
        hyDriver.setValidPeriodFrom(
                DateUtils.getStrToDate(  importHyDriverDTO.getValidPeriodFrom())
        );
        hyDriver.setValidPeriodTo(
                DateUtils.getStrToDate( importHyDriverDTO.getValidPeriodTo())
        );
        hyDriver.setQualificationCertificate(importHyDriverDTO.getQualificationCertificate());
        hyDriver.setTelephone(importHyDriverDTO.getTelephone());

        //选填
        hyDriver.setUserId(userId);
        hyDriver.setExaminRemark(importHyDriverDTO.getRemark());
        hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());

        hyDriver.setIdcardValidFrom(
                DateUtils.getStrToDate(importHyDriverDTO.getIdcard_valid_from())
        );

        hyDriver.setDrivingLicense(importHyDriverDTO.getDriving_license());
        hyDriver.setIdcardExpiredDate(
                DateUtils.getStrToDate(importHyDriverDTO.getIdcard_expired_date())
        );
        hyDriver.setNation(importHyDriverDTO.getNation());
        if (StrUtil.isNotEmpty(importHyDriverDTO.getAddress())) {
            hyDriver.setAddress(importHyDriverDTO.getAddress());
        } else {
            hyDriver.setAddress("--");
        }

        hyDriver.setBirthday(
                DateUtils.getStrToDate(importHyDriverDTO.getBirthday())
        );

        hyDriver.setIssueStartDate(
                DateUtils.getStrToDate(importHyDriverDTO.getIssueStartDate())
        );

        //Added at 2023-07-14 for 增加图片URL导入
        if (StrUtil.isNotEmpty(importHyDriverDTO.getIdcardImg())) {
            hyDriver.setIdcardImg(importHyDriverDTO.getIdcardImg());
        }

        if (StrUtil.isNotEmpty(importHyDriverDTO.getIdcardImgBack())) {
            hyDriver.setIdcardImgBack(importHyDriverDTO.getIdcardImgBack());
        }

        if (StrUtil.isNotEmpty(importHyDriverDTO.getDriverImg())) {
            hyDriver.setDriverImg(importHyDriverDTO.getDriverImg());
        }

        if (StrUtil.isNotEmpty(importHyDriverDTO.getDriverImg2())) {
            hyDriver.setDriverImg2(importHyDriverDTO.getDriverImg2());
        }

        if (StrUtil.isNotEmpty(importHyDriverDTO.getQualificationImg())) {
            hyDriver.setQualificationImg(importHyDriverDTO.getQualificationImg());
        }

        hyDriver.setDirverImportFlag("1");

        return hyDriver;
    }

}
